package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.ml.EvaluateDataFrameRequest;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
            //准备request
            SearchRequest request = new SearchRequest("hotel");

            //准备DSL
            //query
            buildBasicQuery(params,request);

            //分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page-1)*size).size(size);

            //排序(根据location坐标点按公里数升序排序)
            String location = params.getLocation();
            if(location != null && !location.equals("")){
               request.source().sort(SortBuilders.geoDistanceSort("location",new GeoPoint(location)).order(SortOrder.ASC).unit(DistanceUnit.KILOMETERS));
            }

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            return handleResponse(response);
        } catch (IOException e) {
            throw new RuntimeException(e);//继续向外抛出异常，暂不处理
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try{
            //准备request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            //query
            buildBasicQuery(params,request);
            //设置size-不要文档数据
            request.source().size(0);
            //聚合
            buildAggregation(request);
            //发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Map<String,List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            //根据名称获取聚合后的品牌结果
            List<String> brandList = getAggByName(aggregations,"brandAgg");
            //放入map
            result.put("brand",brandList);
            //根据名称获取聚合后的城市结果
            List<String> cityList = getAggByName(aggregations,"cityAgg");
            //放入map
            result.put("city",cityList);
            //根据名称获取聚合后的星级结果
            List<String> starList = getAggByName(aggregations,"starAgg");
            //放入map
            result.put("starName",starList);
            return result;
        } catch(IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override //自动补全查询
    public List<String> getSuggestions(String prefix) {
        try {
            //准备request
            SearchRequest request = new SearchRequest("hotel");
            //准备DSL
            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "suggestions",
                    SuggestBuilders.completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true) //跳过重复
                            .size(10) //pageSize
            ));
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //根据补全查询名称，获取补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");
            //获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            //遍历
            ArrayList<String> list = new ArrayList<>(options.size()); //options.size():限定list的大小
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insertById(Long id) {
        try {
            //根据id查询酒店数据
            Hotel hotel = getById(id);
            //转换为索引库文档类型(经纬度)
            HotelDoc hotelDoc = new HotelDoc(hotel);

            //准备request对象
            IndexRequest request = new IndexRequest("hotel").id(hotelDoc.getId().toString());
            //准备json文档
            request.source(JSON.toJSONString(hotelDoc), XContentType.JSON);
            //发送请求
            client.index(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void deleteById(Long id) {
        try {
            //准备request
            DeleteRequest request = new DeleteRequest("hotel",id.toString());
            //发送请求
            client.delete(request,RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<String> getAggByName(Aggregations aggregations,String aggName) {
        //根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        //获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        //遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            //获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }


    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders.terms("brandAgg").field("brand").size(100));
        request.source().aggregation(AggregationBuilders.terms("cityAgg").field("city").size(100));
        request.source().aggregation(AggregationBuilders.terms("starAgg").field("starName").size(100));
    }

    private void buildBasicQuery(RequestParams params,SearchRequest request) {
        //默认的算分原始查询
        //构建BooleanQuery:多条件查询需要使用BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //关键字搜索:query
        String key = params.getKey();
        if(key == null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery()); //参与算分，影响性能
        }else{
            boolQuery.must(QueryBuilders.matchQuery("all",key));//参与算分，影响性能
        }
        //条件过滤
        //城市条件
        if(params.getCity() != null && !params.getCity().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("city", params.getCity()));//不参与算分，不影响性能
        }
        //品牌条件
        if(params.getBrand() != null && !params.getBrand().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));//不参与算分，不影响性能
        }
        //星级条件
        if(params.getStarName() != null && !params.getStarName().equals("")){
            boolQuery.filter(QueryBuilders.termQuery("starName", params.getStarName()));//不参与算分，不影响性能
        }
        //价格
        if(params.getMinPrice() != null && params.getMaxPrice() != null){
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice()));//不参与算分，不影响性能
        }

        //算分控制
        FunctionScoreQueryBuilder functionScoreQuery =
                QueryBuilders.functionScoreQuery(
                        boolQuery, //原始查询，相关性算分查询
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{ //function Score 的数组
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder( //其中的一个functionScore元素
                                        QueryBuilders.termQuery("isAD",true), //过滤条件
                                        ScoreFunctionBuilders.weightFactorFunction(10)//算法函数，锚定的算分乘以10
                                )
                        });

        request.source().query(functionScoreQuery);

    }

    private PageResult handleResponse(SearchResponse response) {
        //解析响应
        SearchHits searchHits = response.getHits();
        //获取总条数
        long total = searchHits.getTotalHits().value;
        //文档数据
        SearchHit[] hits = searchHits.getHits();
        //遍历
        List<HotelDoc> hotels = new ArrayList<>();
        for(SearchHit hit : hits){
            //获取文档source
            String json = hit.getSourceAsString();
            //反序列化
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);
            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if(sortValues.length > 0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }
            hotels.add(hotelDoc);
        }
        //封装返回
        return new PageResult(total,hotels);
    }
}
